from django.http import HttpResponse
from django.db import IntegrityError
from django.template import Context,loader
from django.shortcuts import render_to_response, redirect
from django.contrib.auth.decorators import login_required

from game.encounter.models import combatEncounter, engagedPlayer
from game.profile.models import profile
from game.combat.models import combat, combatSide
from game.combat.views import showCombat, combatURLPath
from game.common.logger import logger

def showEncounter(request, enc):
    #takes a request and an encounter and calls necessary functions
    response = HttpResponse()
    c = Context()
    if isinstance(enc, combatEncounter):
        #Combat time, start the fight
        logger.debug("Getting user from session using id %s"%(request.session['profileID']))
        playerProfile = profile.objects.get(id = request.session['profileID'])
        playerGroup = combatSide.objects.create()
        logger.debug("user %s is starting combat"%(playerProfile.user.username))
        #create a group to hold the encountered monsters
        monsterGroup = combatSide.objects.create()
        #create the combat and add initial dialog
        cmb = combat.objects.create(sideA = playerGroup, sideB = monsterGroup)
        cmb.addMessage(enc.message)
        #Generate combatants for the encounter
        logger.debug("Adding enemies to combat")
        for indAndCont in enc.getIndividuals():
            ind = indAndCont[0]
            cont = indAndCont[1]
            #add the individuals to combat
            cmb.addIndividualToCombat(ind, monsterGroup, control=cont)
            logger.debug("%s added to combat"%(ind))
            #add the players individuals to combat
            logger.debug("Adding player's monsters to combat")
        for ind in playerProfile.group.allMonsters():
            cmb.addIndividualToCombat(ind, playerGroup)
            logger.debug("%s added to combat"%(ind))
            #ready the first combatant
            logger.debug("All monsters added to combat, setting the first combatant")
            cmb.getNextCombatant()
            #engage the player
        try:
            engagedPlayer.objects.create(profile = playerProfile, encounter = enc, combat = cmb)
        except Exception, e:
            logger.error("Tried to initiate combat while the player was already in combat: %s")
        return redirect(combatURLPath)
        